Array foreach
Assume we have an array of ages
and you want to loop (or iterate) through each item in the array.
This is how you do it in JavaScript,
const ages = [23, 56, 42, 50];
ages.forEach(function (age) {
// do something with individual age
console.log(age);
});
Using console.log
inside the .forEach
method helps to visualize the transition from array to array item.
The .forEach(callback)
method executes the callback
function for each item in the array. Callbacks will be covered in greater detail in the following chapter. For the time being, let us begin with a basic definition.
A callback
is a function definition that is passed to another function as an argument. Here's the callback function from our previous example,
function(age) {
// do something with individual age
console.log(age);
}
When a age
is received, this callback function logs it to the console. Because it is not being executed, this is a function definition. It only defines the function's actions. This function definition, however, is passed as an argument to the .forEach()
method,
ages.forEach(insert_callbach_here);
By combining both, function definition is passed as an argument to the .forEach()
method. Then we get,
ages.forEach(function (age) {
// do something with individual age
console.log(age);
});
and the code will log every age of the array as shown below,
23
56
42
50
- When learning about callbacks, a common question is how JavaScript knows that grades become grade in the callback parameter. The answer is that it does not!
- JavaScript doesn't care what you call your variables, it will always (in the case of .forEach) look for the first parameter you define in your callback function and pass the appropriate value to it.
So the following code works (but please don't use it),
ages.forEach(function (x) {
// this works, but avoid using generic variable names
console.log(x);
});
- So this works because JavaScript looks for the first parameter, x, and then calls the callback and assigns a value to x every time.
Even if it works, you should always use descriptive variable names.